package com.room.search.service.permission;

import com.room.search.domain.RoomUser;
import com.room.search.exception.CommonException;
import com.room.search.repository.RoomUserRepository;
import com.room.search.security.SecurityUtils;
import com.room.search.util.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * By   : ghd.bright
 * Time : 2022/2/15
 * Description:
 */
@Service("ss")
public class PermissionService {
    /**
     * 所有权限标识
     */
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 管理员角色权限标识
     */
    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMETER = ",";


    private final RoomUserRepository repository;

    public PermissionService(RoomUserRepository repository) {
        this.repository = repository;
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission) {
        if (StringUtils.isEmpty(permission)) {
            return false;
        }
        String username = SecurityUtils.getCurrentUserLogin().orElse(null);
        if (username == null) {
            throw new CommonException("当前没有用户登录");
        }

        RoomUser roomUser = repository.findByAccount(username).orElse(null);

        if (Objects.isNull(roomUser)) {
            return false;
        }
        return hasPermissions(roomUser.getPerms(), permission);
    }

    /**
     * 判断是否包含权限
     *
     * @param userPermissions 权限列表
     * @param permission      权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(String userPermissions, String permission) {
        Set<String> permissions = Arrays.stream(userPermissions.split(ROLE_DELIMETER)).collect(Collectors.toSet());
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }
}
